package 网络编程项目.login.utiles;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

public class ImageUtil {

  public static ImageIcon change(ImageIcon image, int width) {
    int height = image.getIconHeight() * width / image.getIconWidth();
    Image img = image.getImage().getScaledInstance(width, height, Image.SCALE_DEFAULT);
    image.setImage(img);
    return image;
  }

  public static void reduceImg(String imgsrc, String dstName, int width) {
    try {
      File srcfile = new File(imgsrc);
      if (!srcfile.exists()) {
        return;
      }
      BufferedImage src = ImageIO.read(srcfile);
      int widthdist = src.getWidth();
      int height = src.getHeight() * width / widthdist;

      BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

      tag.getGraphics().drawImage(src.getScaledInstance(width, height, Image.SCALE_SMOOTH), 0, 0, null);
      String formatName = dstName.substring(dstName.lastIndexOf(".") + 1);
      ImageIO.write(tag, formatName, new File(dstName));

    } catch (IOException ex) {
      ex.printStackTrace();
    }
  }

  public static String getImageName() {
    return UUID.randomUUID().toString().replaceAll("-", "");
  }

}
